package software.lib.action;

import lsh.LshPackage.Pair;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import software.lib.entity.Gig;
import software.lib.entity.Record;
import software.lib.entity.RecordGig;
import software.lib.entity.User;
import software.lib.entity.graph.Node;
import software.lib.exception.NoSuchEntityException;
import software.lib.service.LshCaller;
import software.lib.service.NemaService;
import software.lib.util.IgnoreFieldProcessorImpl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Wang on 2017/5/19.
 */
@Controller
public class QueryAction {
    @RequestMapping(value = "/init",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    public @ResponseBody
    Object initQuery(String title, HttpSession session){
        Map<String, Object> info = lshCaller.query(title);
        session.setAttribute("title",title);
        Pair[] idlist = (Pair[]) info.get("lsh");
        session.setAttribute("lsh",idlist);
        info.remove("lsh");
//        session.setAttribute("info",info);

        JSONObject jsonObject = JSONObject.fromObject(info);
        return jsonObject;
    }

    @RequestMapping(value = "/nema",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    public @ResponseBody
    Object nemaQuery(@RequestParam Map<String,Object> input, HttpSession session){
        Pair[] idlist = (Pair[]) session.getAttribute("lsh");
//        Map<String, String> input = new TreeMap<>();

        Map<String, String> inputMap = input.entrySet().stream()
                .map(entry -> new String[]{entry.getKey(),entry.getValue().toString()} )
                .collect(Collectors.toMap(x->x[0],x->x[1]));
        Object tags = input.get("tags");
        if(tags instanceof Array){
            String[] tagStr = (String[]) tags;
            Optional<String> tgs = Arrays.stream(tagStr).reduce((s, s2) -> s+","+s2);
            if (tgs.isPresent()){
                inputMap.put("tags",tgs.get());
            }
        }

        inputMap.put("Language",inputMap.get("language"));

        session.setAttribute("userquery",inputMap);
        System.out.println(inputMap);

        org.apache.commons.lang3.tuple.Pair<List<Node>, List<Node>> resultPair =
            nemaService.doNema(inputMap,idlist);

        List<Node> gigsByCostDesc = resultPair.getLeft();

        System.out.println(gigsByCostDesc);

        List<Node> gigsByScoreDesc = resultPair.getRight();

        //暂只返回 按照Cost降序的gigs
        JSONArray jarr = nemaService.transferToJSON(gigsByCostDesc);
        session.setAttribute("gigList",jarr);

        return jarr;
    }


    @RequestMapping(value = "/feedback",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    public @ResponseBody
    Object feedback(int chooseId, HttpSession session){
        JSONObject jsonObject = new JSONObject();
        try {
            Record record = new Record();

            Map<String, String> inputMap = (Map<String, String>) session.getAttribute("userquery");
            inputMap.entrySet().stream().forEach(entry -> {
                switch (entry.getKey()){
//                    case "query":
//                        record.setTitle(entry.getValue());
//                        break;
                    case "score":
                        record.setScore(Double.parseDouble(entry.getValue()));
                        break;
                    case "timespan":
                        record.setTimespan(Integer.parseInt(entry.getValue()));
                        break;
                    case "duration":
                        record.setDuration(Integer.parseInt(entry.getValue()));
                        break;
                    case "price":
                        record.setPrice(Integer.parseInt(entry.getValue()));
                        break;
                    case "tags":
                        record.setTags(entry.getValue());
                        break;
                    case "sale_effiency":
                        record.setSale_effiency(Double.parseDouble(entry.getValue()));
                        break;
                    case "country":
                        record.setCountry(entry.getValue());
                        break;
                    case "language":
                        record.setLanguage(entry.getValue());
                        break;
                    case "level":
                        record.setLevel(entry.getValue());
                        break;
                    case "avg_resp_time":
                        record.setAvg_resp_time(Integer.parseInt(entry.getValue()));
                        break;
                }
            });

            String title = (String) session.getAttribute("title");
            record.setTitle(title);

            JSONArray gigList = (JSONArray) session.getAttribute("gigList");
            List<RecordGig> recordGigs= gigList.stream().mapToInt(o -> (((JSONObject)o).getInt("gid")))
                    .<RecordGig>mapToObj(o -> new RecordGig(o)).collect(Collectors.toList());
            record.setGigList(recordGigs);

            record.setChoosedId(chooseId);

            nemaService.addRecord(record);
            jsonObject.put("status",true);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("status",false);
            jsonObject.put("msg",e.getMessage());
        }

        return jsonObject;
    }


    @Autowired
    private NemaService nemaService;

    @Autowired
    private LshCaller lshCaller;

    public void setNemaService(NemaService nemaService) {
        this.nemaService = nemaService;
    }

    public void setLshCaller(LshCaller lshCaller) {
        this.lshCaller = lshCaller;
    }
}
